//
//  EZEnvironmentSwitchKit.m
//  EZEnvironmentSwitchKit
//
//  Created by melo30 on 2019/4/8.
//

#import "EZTestToolManager.h"
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>

@interface EZTestToolManager ()
@property (strong,nonatomic) CMMotionManager *motionManager;

@property (nonatomic, strong) UIViewController * currentViewController;
@end

@implementation EZTestToolManager

static dispatch_once_t onceToken;
+ (EZTestToolManager *)shareTestToolManager
{
    static EZTestToolManager *manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initializeConfig {
    self.motionManager = [[CMMotionManager alloc] init];//一般在viewDidLoad中进行
    self.motionManager.accelerometerUpdateInterval = .1;//加速仪更新频率，以秒为单位
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterFore) name:UIApplicationWillEnterForegroundNotification object:[UIApplication sharedApplication]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackgound) name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]];
    [self startAccelerometer];
}

- (void)enterBackgound {
    [self.motionManager stopAccelerometerUpdates];
}

- (void)enterFore {
    [self startAccelerometer];
}

- (void)startAccelerometer {
    //以push的方式更新并在block中接收加速度
    [self.motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc]init]
                                             withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
                                                 [self outputAccelertionData:accelerometerData.acceleration];
                                                 if (error) {
                                                     NSLog(@"motion error:%@",error);
                                                 }
                                             }];
}

- (void)outputAccelertionData:(CMAcceleration)acceleration {
    //综合3个方向的加速度
    double accelerameter =sqrt( pow( acceleration.x , 2 ) + pow( acceleration.y , 2 )
                               + pow( acceleration.z , 2) );
    //当综合加速度大于2.3时，就激活效果（此数值根据需求可以调整，数据越小，用户摇动的动作就越小，越容易激活，反之加大难度，但不容易误触发）
    if (accelerameter > 2.3f) {
        //立即停止更新加速仪（很重要！）
//        [self.motionManager stopAccelerometerUpdates];
        __weak typeof(self) wself = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"摇一摇");
            //UI线程必须在此block内执行，例如摇一摇动画、UIAlertView之类
            if (!wself.isShow) {
                UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
                UIViewController *viewController = window.rootViewController;
                while (viewController.presentedViewController) {
                    viewController = viewController.presentedViewController;
                }
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"EZEnvironmentSwitch" bundle:[wself getCurrentBundle]];
                wself.currentViewController = [storyboard instantiateInitialViewController];
                [viewController presentViewController:wself.currentViewController animated:YES completion:nil];
            }
            wself.isShow = YES;
        });
    }
}


- (NSBundle *)getCurrentBundle {
    NSString *mainBundlePath = [NSBundle mainBundle].bundlePath;
    NSString *bundlePath = [NSString stringWithFormat:@"%@/%@",mainBundlePath,@"EZEnvironmentSwitchKit.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    if (bundle == nil) {
        bundlePath = [NSString stringWithFormat:@"%@/%@",mainBundlePath,@"Frameworks/EZEnvironmentSwitchKit.framework/EZEnvironmentSwitchKit.bundle"];
        bundle = [NSBundle bundleWithPath:bundlePath];
    }
    return bundle;
}

@end
